import Vue from 'vue';
import Vuex from 'vuex';
import pkg from '../../package.json';
import Util from '../utils/util';
import Model from '../model';
import Auth from '../router/auth';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    title: '智慧建管系统',
    hasLogin: false,
    count: 0,
    // 是否显示loading状态
    isLoading: false,
    // 缓存随机数
    randomList: [],
    // 当前运行环境
    environment: pkg.environment,
    clientLanguage: pkg.clientLanguage,
    // 服务信息
    serverInfo: {},
    // 用户信息
    userInfo: {},
    // 该用户的功能权限列表
    roleList: [],
    // 公司及管理系统的项目列表
    projectInfo: [],
    // 当前项目信息
    currentProjectInfo: {},
    // 当前进入的项目id
    currentProjectId: '',
    // 组织架构当前选中的值
    currentOrgKey: '',
    // 当前节点是否为组织（否则为部门）
    hasOrg: true,
    // 路由即将要进入的目标信息
    routeToInfo: {},
    // 当前路由正要离开信息
    routeFromInfo: {},
    // 当前返回的权限数据
    roleData: [],
    // 过滤权限后的项目级菜单数据
    menuList: [],
    // 过滤权限后的数据
    menuTree: [],
    isAdmin: false,
    // 页面权限数据
    pageRoles: [],
    hasToProject: false,
    // 是否已经获取权限
    hasRole: false,
    // 项目详情tab标识
    tabId: '1'
  },
  getters: {
    /**
     * 语言
     */
    language: state => {
      return state.clientLanguage;
    },
    // 当前页面权限
    pageAuth: state => {
      const { pageRoles, routeToInfo: { path }} = state;
      return pageRoles.find(v => v.path === path) || {};
    },
  },
  mutations: {
    /**
     * 更新路由即将要进入的目标信息
     */
    updateRouteToInfo(state, route) {
      state.routeToInfo = route;
    },
    /**
     * 更新当前路由正要离开信息
     */
    updateRouteFromInfo(state, route) {
      state.routeFromInfo = route;
    },
    /**
     * 更新随机数
     * @param state
     * @param randomStr: 随机数
     */
    updateRandomList(state, randomStr) {
      state.randomList.push(randomStr);
    },
    /**
     * 更新登录状态
     */
    updateLoginStatus(state, status) {
      state.hasLogin = status;
    },
    /**
     * 更新用户信息
     */
    updateUserInfo(state, data) {
      state.userInfo = {
        ...data
      };
    },
    /**
     * 更新公司及管理系统的项目列表
     */
    updateProjectInfo(state, data) {
      state.projectInfo = data;
    },
    /**
     * 更新用户权限
     */
    updateRoleList(state, data) {
      state.roleList = [...data];
    },
    /**
     * 更新当前项目信息
     */
    updateCurrentProjectInfo(state, data = {}) {
      state.currentProjectInfo = {
        ...data
      };
    },
    /**
     * 更新当前项目id
     */
    updateCurrentProjectId(state, data) {
      state.currentProjectId = data;
    },
    /**
     * 更新组织架构当前选中值
     */
    updateCurrentOrgKey(state, id) {
      state.currentOrgKey = id || '';
    },
    /**
     * 更新当前节点是否为组织（否则为部门）
     * @param state
     * @param value {Boolean} 当前节点是否为组织（否则为部门）
     */
    updateHasOrg(state, value) {
      state.hasOrg = value;
    },
    // 更新权限
    updateRoleData(state, data = []) {
      state.roleData = data;
    },
    // 更新菜单
    updateMenuList(state, data) {
      state.menuList = data;
    },
    // 更新菜单
    updateMenuTree(state, data) {
      state.menuTree = data;
    },
    // 更新页面的权限
    updatePageAuth(state, data) {
      state.pageRoles = data;
    },
    // 更新是否进入项目模块的标记
    updateHasToProject(state, data = false) {
      state.hasToProject = data;
    },
    // 更新权限标记
    updateHasRole(state, data = false) {
      state.hasRole = data;
    },
    updateTabId(state, data = '1') {
      state.tabId = data;
    },
    /**
     * 清除登录信息
     */
    clearUserInfo(state) {
      // 删除用户信息
      Object.keys(state.userInfo).forEach((key) => {
        state.userInfo[key] = '';
      });
      state.roleData = [];
      state.menuList = [];
      state.menuTree = [];
      state.pageRoles = [];
      state.isAdmin = false;
      state.hasRole = false;
      state.hasToProject = false;
      state.currentProjectId = '';
      Util.deleteLocalStorage('user_info');
      Util.deleteLocalStorage('x-access-token');
      // 删除当前项目id
      Util.deleteLocalStorage('projectId');
    },
  },
  actions: {
    /**
     * 获取当前用户的信息
     * @desc id {?String} 用户id
     */
    async getUserInfo({ commit, state }, id) {
      let userId = id;
      if (!userId) {
        try {
          const userInfo = Util.getLocalStorage('user_info');
          userId = JSON.parse(userInfo).userId;
        } catch (e) {}
      }
      const { success, data: {
        data
      }} = await Model.getUserInfoById({
        userId
      });
      if (success && data) {
        commit('updateUserInfo', data);
        try {
          const userInfo = JSON.stringify(data);
          Util.setLocalStorage('user_info', userInfo);
        } catch (e) {}
      }
    },
    /**
     * 获取项目信息
     * @desc options {Object} 请求参数
     */
    async getProjectInfo({ commit, state }, options = {}) {
      let result = {};
      result = await Model.getProjectList(options);
      const { success, data: { data }} = result;
      if (success && Array.isArray(data)) {
        if (state.currentProjectId) {
          const currentInfo = data.find(item => (
            item.projectId === state.currentProjectId
          ));
          commit('updateCurrentProjectInfo', currentInfo);
        } else {
          const projectId = data[0] && data[0].projectId;
          if (projectId) {
            store.commit('updateCurrentProjectId', projectId);
            commit('updateCurrentProjectInfo', data[0]);
          }
        }
        commit('updateProjectInfo', data);
      }
      return result;
    },
    /**
     * 获取当前用户项目信息
     * @desc options {Object} 请求参数
     */
    async getProjectListByUser({ commit, state }, options = {}) {
      let result = {};
      const params = {
        userId: state.userInfo.uuid,
        ...options
      };
      result = await Model.getUserProject(params);
      const { success, data: { data }} = result;
      if (success && Array.isArray(data)) {
        if (state.currentProjectId) {
          const currentInfo = data.find(item => (
            item.projectId === state.currentProjectId
          ));
          commit('updateCurrentProjectInfo', currentInfo);
        } else {
          const projectId = data[0] && data[0].projectId;
          if (projectId) {
            store.commit('updateCurrentProjectId', projectId);
            commit('updateCurrentProjectInfo', data[0]);
          }
        }
        commit('updateProjectInfo', data);
      }
      return result;
    },
    /**
     * @description 获取当前用户菜单信息
     */
    async getMenuList({ commit, state }) {
      const {
        userInfo,
        currentProjectId
      } = state;
      let newMenus = [];
      let authMenu = [];
      const parmas = {
        userId: userInfo.uuid
      };
      if (currentProjectId) parmas.projectId = currentProjectId;
      const { success, data: {
        data
      }} = await Model.getUserPermissionTree(parmas);
      if (success) {
        const { menus, authList, filterMenus } = Auth.setMenuList(data);
        newMenus = [...menus];
        authMenu = [...filterMenus];
        commit('updateRoleData', data || []);
        commit('updateMenuList', menus);
        commit('updateMenuTree', filterMenus);
        commit('updatePageAuth', authList);
        commit('updateHasRole', true);
        currentProjectId && commit('updateHasToProject', true);
      }
      return {
        success,
        data,
        authMenu,
        menus: newMenus
      };
    },
  },
  modules: {}
});

export default store;
